package thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @Author fallrain
 * @Description 第三种：通过Callable接口,重写run()方法创建
 * 1:创建Callable接口的实现类,并重写call()方法
 * 2:创建Callable实现类的实例,使用FutrueTask包装Callable实例
 * 3:使用FutrueTask的实例,传入 new Thread(xxx)创建一个线程对象
 * 4:调用线程对象的start()方法启动线程
 * @Date 2022/2/22 9:54
 * @Version 1.0
 */
public class CreateByCallable {
    public static void main(String[] args) {
        FutureTask futureTask = new FutureTask(new CallableThread());
        new Thread(futureTask).start();
        try {
            System.out.println(futureTask.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

class CallableThread implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for (int i = 0; i < 3; i++) {
            sum +=i;
        }
        return sum;
    }
}
